<template>
  <div>
    <tableTep
      :tableConfig="state.tableConfig"
      :tableHeader="state.tableHeader"
      :tableHandleList="state.tableHandleList"
      :searchList="state.searchList"
      :searchForm="state.searchForm"
      :getDataAsync="getDeptList"
      @removeHandle="removeHandle"
      @addHandle="addHandle"
      @editHandle="editHandle"
      @returnDataList="returnDataList"
      ref="tableTepRef"
    >
      <template v-slot:content>
        <el-col :span="6">
          <el-button type="primary" @click="searchHandle">搜索</el-button>
          <el-button type="primary" @click="resetHandle">重置</el-button>
        </el-col>
      </template>
      <template v-slot:businessHandle>
        <el-button type="primary" @click="addState">新增</el-button>
      </template>
    </tableTep>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :before-close="handleClose"
      :title="dialogTitle"
      width="60%"
    >
      <FormTep
        :formList="state.addFormList"
        :formData="state.addForm"
        ref="FormTepRef"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCanCel">取消</el-button>
          <el-button type="primary" @click="submitHandle">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name:'Dept'
}
</script>
<script setup>
import tableTep from "@/components/tableTep/index.vue";
import FormTep from "@/components/FormTep/index.vue";
import { reactive, ref, inject, computed, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { clearObj } from "@/utils/utils.js";
const { getDeptList, getAllUserList, addDept, deleteDept, upDateDept } =
  inject("$api");
import dayjs from "dayjs";

let tableTepRef = ref(null);
let FormTepRef = ref(null);
let menuTree = ref(null);

const state = reactive({
  tableHeader: [
    {
      prop: "deptName",
      label: "部门名称",
    },
    {
      prop: "userName",
      label: "负责人",
      propDefine: (row) => {
        return `<span>${row.userName?.userName || "暂无"}</span>`;
      },
    },
    {
      label: "更新时间",
      prop: "updateTime",
      propDefine: (row) => {
        return `<span>${dayjs(row.updateTime).format(
          "YYYY-MM-DD HH:mm"
        )}</span>`;
      },
    },
    {
      prop: "createTime",
      label: "创建时间",
      propDefine: (row) => {
        return `<span>${dayjs(row.createTime).format(
          "YYYY-MM-DD HH:mm"
        )}</span>`;
      },
    },
  ],
  tableConfig: {
    showIndex: true, //是否显示序号
    tableHeight: 600, //表格高度
    isSelection: true,
    tableSize: 1,
    isRemember: true,
    defaultOptions: {
      border: true,
    },
    handleOption: {
      handleName: "操作", // 操作列表头名称
      width: 250,
      align: "center",
    },
  },
  tableHandleList: [
    // 具体操作
    {
      label: "编辑",
      handle: "editHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "primary",
      },
    },
    // 具体操作
    {
      label: "删除",
      handle: "removeHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "danger",
      },
    },
    {
      label: "新增",
      handle: "addHandle",
      btnAttr: {
        //按钮配置项
        size: "mini",
        type: "danger",
      },
    },
  ],
  searchList: [
    {
      name: "deptName", //字段名
      type: "TextMoudel", //类型
      title: "部门名称",
      required: false, // 必填
      span: 6,
    },
  ],
  searchForm: {
    deptName: "",
  },
  addFormList: [
    {
      name: "parentIdList", //字段名
      type: "CascaderMoudel", //类型
      title: "上级部门",
      required: false, // 必填
      span: 12,
      definProps: {
        clearable: true,
        props: { checkStrictly: true, value: "_id", label: "deptName" },
        disabled: false,
      },
      options: [],
      change: function (value) {
        state.addForm.parentId = value ? value[value.length - 1] : null;
      },
    },
    {
      name: "deptName", //字段名
      type: "TextMoudel", //类型
      title: "部门名称",
      required: true, // 必填
      span: 24,
    },
    {
      name: "userName", //字段名
      type: "SelectMoudel", //类型
      title: "负责人",
      trigger: ["change"],
      required: true, // 必填
      span: 12,
      // 选择项
      options: [],
    },
    {
      name: "userEmail", //字段名
      type: "TextMoudel", //类型
      title: "邮箱",
      required: true, // 必填
      span: 24,
    },
  ],
  addForm: {
    parentId: null,
    parentIdList: [],
    deptName: "",
    user: "",
    userName: "",
    userEmail: "",
  },
  deptList: [],
});
const dialogVisible = ref(false);
const dialogTitle = ref("");

//获取所有人员数据
onMounted(() => {
  getAllUserList().then((res) => {
    let data = res.map((v) => {
      return {
        value: v._id,
        label: v.userName,
      };
    });
    state.addFormList.map((v) => {
      if (v.name === "userName") {
        v.options = data;
        console.log(data);
      }
    });
  });
});
const handleClose = () => {
  dialogVisible.value = false;
  dialogTitle.value = "";
  state.addForm = clearObj(state.addForm);
};
/**
 * @description: 回显列表数据
 * @param {*}
 * @return {*}
 */
const returnDataList = (value) => {
  let res = state.addFormList.find((v) => v.name === "parentIdList");
  res.options = value;
};

/**
 * @description: 移出操作
 * @param {*}
 * @return {*}
 */
const removeHandle = (row) => {
  ElMessageBox.confirm(`是否删除名称为  ${row.deptName}  的菜单?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteDept({ _id: row._id });
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    await tableTepRef.value.refreshData();
  });
};
/**
 * @description: 修改数据
 * @param {*}
 * @return {*}
 */
const editHandle = (row) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑";
  console.log(row);
  Object.assign(state.addForm, row, { userName: row.userName?._id });
  let res = state.addFormList.find((v) => v.name === "parentIdList");
  res.definProps.disabled = true;
};

/**
 * @description: 当前栏下的添加操作
 * @param {*}
 * @return {*}
 */
const addHandle = (row) => {
  let res = state.addFormList.find((v) => v.name === "parentIdList");
  res.definProps.disabled = true;
  dialogTitle.value = "新增";
  state.addForm.parentIdList =
    row.parentIdList && row.parentIdList.length === 0
      ? [row._id]
      : [...row.parentIdList, row._id];
  state.addForm.parentId = row._id;
  dialogVisible.value = true;
};

/**
 * @description: 搜索刷新列表
 * @param {*}
 * @return {*}
 */
const searchHandle = () => {
  tableTepRef.value.refreshData();
};

/**
 * @description:重置搜索
 * @param {*}
 * @return {*}
 */
const resetHandle = () => {
  state.searchForm = clearObj(state.searchForm);
  tableTepRef.value.refreshData();
};

/**
 * @description: 添加操作
 * @param {*}
 * @return {*}
 */
const addState = () => {
  let showDis = state.addFormList.find((v) => v.name === "parentIdList");
  showDis.definProps.disabled = false;
  dialogVisible.value = true;
  dialogTitle.value = "新增";
};
/**
 * @description: 取消
 * @param {*}
 * @return {*}
 */
const handleCanCel = () => {
  dialogVisible.value = false;
  dialogTitle.value = "";
  state.addForm = clearObj(state.addForm);
};
/**
 * @description: 提交
 * @param {*}
 * @return {*}
 */
const submitHandle = async () => {
  let res = await FormTepRef.value.submitForm();
  if (res) {
    if (dialogTitle.value === "新增") {
      addDept(state.addForm).then((data) => {
        dialogVisible.value = false;
        dialogTitle.value = "";
        //TODO
        ElMessage({
          message: "创建成功",
          type: "success",
        });
        state.addForm = clearObj(state.addForm);

        let showDis = state.addFormList.find((v) => v.name === "parentIdList");
        showDis.definProps.disabled = false;

        tableTepRef.value.refreshData();
      });
    }
    if (dialogTitle.value === "编辑") {
      upDateDept(state.addForm).then((data) => {
        dialogVisible.value = false;
        dialogTitle.value = "";
        //TODO
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        state.addForm = clearObj(state.addForm);

        let showDis = state.addFormList.find((v) => v.name === "parentIdList");
        showDis.definProps.disabled = false;

        tableTepRef.value.refreshData();
      });
    }
  }
};
</script>
<style scoped>
</style>
